<?
if (preg_match("#" . basename(__FILE__) . "#", $_SERVER['PHP_SELF'])) {
    die('This page cannot be called directly.') ;
}

require_once 'includes/AjaxRes.php'; //System Debug...
class ajax_processcart {

    function playme(){
        $code = Url::getParam('code');
        //yêu cầu đặt tên $code=tên của method trong class

        if (method_exists($this, $code)) {
            $this->$code();
        }
        else
        {
            $this->home();
        }
    }

    function home(){
        global $display;
        die("Nothing to do 1213...");
    }

    function cart(){
        global $display;
        $ajax_response = new AjaxRes();

//        $supplied_token = Url::get('__okaToken','');
//        if (!isset($_SESSION['token'], $_SESSION['token-expires'])) {
//            $ajax_response->type = AjaxRes::ERROR;
//            $ajax_response->message = 'Request không hợp lệ';
//            echo $ajax_response->toString();
//            return;
//        }
//
//        $token = $_SESSION['token'];
//        $expires = $_SESSION['token-expires'];
//
//        if ($expires < time() || $token != $supplied_token) {
//            $ajax_response->type = AjaxRes::ERROR;
//            $ajax_response->message = 'Request không hợp lệ';
//            echo $ajax_response->toString();
//            return;
//        }

        //thông tin user
        if(User::is_login()){
            $user = DB::select("user","id=".User::id());

            //Get info from cookies if exist
            if(isset($_COOKIE["cus_name"]) && isset($_COOKIE["cus_phone"]) && isset($_COOKIE["cus_email"])){
                if($_COOKIE["cus_name"] != "" && $_COOKIE["cus_phone"] != "" && $_COOKIE["cus_email"] != ""){
                    $display->add('name', $_COOKIE["cus_name"]);
                    $display->add('phone', $_COOKIE["cus_phone"]);
                    $display->add('email', $_COOKIE["cus_email"]);
                    if (isset($_COOKIE["cus_note"])){
                        $display->add('note', $_COOKIE["cus_note"]);
                    }
                    if (isset($_COOKIE["cus_cmnd"])){
                        $display->add('cmnd', $_COOKIE["cus_cmnd"]);
                    }
                }else{
                    $display->add('name', $user['full_name']);
                    $display->add('phone', $user['mobile_phone']);
                    $display->add('email', $user['email']);
                    $display->add('note', "");
                }
            }else{
                $display->add('name', $user['full_name']);
                $display->add('phone', $user['mobile_phone']);
                $display->add('email', $user['email']);
                $display->add('note', "");
            }

            //danh bạ
            $contacts = DB::select_all('cart_contact', 'user_id='.$user['id']);
            $display->add('contacts', $contacts);
            $display->add('numcontacts', sizeof($contacts));

            //tính tiền
            $from_date = Url::get('from_date','');
            $to_date = Url::get('to_date','');
            $room_booked = Url::get("room");
            $hotel_id = Url::get("hotel_id");
            $display->add('from_date', $from_date);
            $display->add('to_date', $to_date);

            $hotel_active = true;
            if($hotel_id){
                $hotel = Db_Hotel::getHotelById($hotel_id);
                $display->add('hotel_name', $hotel['name']);
                if($hotel['status'] == 2){
                    //trường hợp ks đã bị ẩn
                    $hotel_active = false;
                }
            }else{
                $hotel_active = false;
            }
            if(!$hotel_active){
                $ajax_response->type = AjaxRes::ERROR;
                $ajax_response->message = 'Khách sạn đã ngừng hoạt động';
                echo $ajax_response->toString();
                return;
            }

            if($from_date==''||$to_date==''||strtotime($from_date)>=strtotime($to_date)){
                $rooms=false;
                $ajax_response->type = AjaxRes::WARNING;
                echo $ajax_response->toString();
                return;
            }else{
                $get_from_date = explode('-',$from_date);
                $int_from_date = mktime("0","0","0",$get_from_date[1],$get_from_date[0],$get_from_date[2]);
                $get_to_date = explode('-',$to_date);
                $int_to_date = mktime("0","0","0",$get_to_date[1],$get_to_date[0],$get_to_date[2]);
                $datediff = $int_to_date - $int_from_date;
                $num_days = floor($datediff/(60*60*24));

                $rooms = Db_Room::getRoomsAvailableByHotelId($hotel_id,$int_from_date,$int_to_date);
                $price = 0;
                $room_list = array();
                foreach($rooms as $r){
                    if(isset($room_booked[$r['id']])){
                        $price += $room_booked[$r['id']]*$r['price'];
                        $room = array();
                        $room['name'] = $r['name'];
                        $room['num_days'] = $num_days;
                        $room['quantity'] = $room_booked[$r['id']];
                        $room['price'] = $r['price'];
                        $room['total_price'] = $room['price'] * $room_booked[$r['id']];
                        if($room['total_price']) $room_list[] = $room;
                    }
                }
                $display->add('room_list', $room_list);
                $display->add('price', $price);
            }
            $display->add('WEB_NAME', WEB_NAME);
            $item = $display->output('processcart', true, 'ProcessCart');
            $ajax_response->type = AjaxRes::SUCCESS;
            $ajax_response->item = $item;
            echo $ajax_response->toString();
        }else{
            $ajax_response->type = AjaxRes::WARNING;
            echo $ajax_response->toString();
        }
    }

    function validate(){
        //thông tin đơn hàng

        $from_date = Url::get('from_date','');
        $to_date = Url::get('to_date','');
        $room_booked = Url::get("room");
        $cus = Url::get("cus");
        $hotel_id = Url::get("hotel_id");
        $type_payment = Url::get("type");
        $roombk = array();

        if($type_payment == '' || $type_payment=='undefined'){
            echo 'wrong_type_payment';
            exit;
        }
        if($from_date==''||$to_date==''){
            $rooms=false;
            echo 'wrong_date';
            exit;
        }else{
            $get_from_date = explode('-',$from_date);
            $int_from_date = mktime("0","0","0",$get_from_date[1],$get_from_date[0],$get_from_date[2]);
            $get_to_date = explode('-',$to_date);
            $int_to_date = mktime("0","0","0",$get_to_date[1],$get_to_date[0],$get_to_date[2]);
            $rooms = Db_Room::getRoomsAvailableByHotelId($hotel_id,$int_from_date,$int_to_date);
            $price = 0;
            $total_room = 0;
            foreach($rooms as $room){
                if(isset($room_booked[$room['id']]) && $room_booked[$room['id']]!=0){
                    $r=Db_BookingProcees::getRoomsAvailableByRoomId($room['id'],$int_from_date,$int_to_date);
                    $total_room += $room_booked[$r[0]['id']];
                    $data = array('id' => $r[0]['id'], 'quantity' => $room_booked[$r[0]['id']], 'price' => $r[0]['price'], 'price_detail' => $r[0]['price_detail']);
                    if($room['promotion']){
                        $data['promotion_id'] = $room['promotion_id'];
                        $data['pro_name'] = $room['pro_name'];
                        $data['price'] = $room['price'];
                        $data['old_price'] = $room['old_price'];
                        $price += $room_booked[$r[0]['id']] * $data['price'];
                    }else{
                        $price += $room_booked[$r[0]['id']] * $r[0]['price'];
                    }
                    $roombk[] = $data;


                }
            }
        }

        //thông tin khách hàng
        if(User::is_login()){
            $user_new = array();
            $user_new['name'] = $cus[0];
            $user_new['organization'] = $cus[5];
            $user_new['phone'] = $cus[1];
            $user_new['email'] = $cus[2];
            $user_new['address'] = $cus[4];
            $user_new['location_id'] = $cus[6];
            $user_new['note'] = $cus[3];
            $user_new['cmnd'] = $cus[7];

            //Set cookie lưu lại thông tin KH
            $time = 60 * 60 * 24 * 365 + TIME_NOW;
            setcookie("cus_name", $user_new['name'], $time, "/");
            setcookie("cus_phone", $user_new['phone'], $time, "/");
            setcookie("cus_email", $user_new['email'], $time, "/");
            setcookie("cus_note", $user_new['note'], $time, "/");
            setcookie("cus_cmnd", $user_new['cmnd'], $time, "/");

            //Thêm vào CSDL
            /*if($cart = Db_BookingProcees::addRoomBookToCart($roombk,$total_room,$int_from_date,$int_to_date,$price,$type_payment,$user_new)){
                //echo $cart;
                $this->send_mail($cart);
            }*/
        }

        $cart = array(
            "hotel_id" => $hotel_id,
            "roombk" => $roombk,
            "total_room" => $total_room,
            "int_from_date" => $int_from_date,
            "int_to_date" => $int_to_date,
            "total" => $price,
            "type_payment" => $type_payment,
            "user" => $user_new
        );

        $_SESSION['cart'] = $cart;

        echo 'success';
    }

    function deleteContact(){
        $id = Url::get('id');
        if(DB::delete('cart_contact', 'id='.$id)){
            echo 1;
        }else{
            echo 0;
        };
    }
    function send_mail($cartId){
        global $display;
        //$cartId = Url::get('cart_id',0);

        if($cartId !== 0){

            $cart = DB::select('cart', 'id='.$cartId, __FILE__ . ' line ' . __LINE__);
            $cart_contact = DB::select('cart_contact', 'id='.$cart['customer_info_id'], __FILE__ . ' line ' . __LINE__);
            if($cart !== null){
                if(User::id() == $cart['user_id']){
                    $booking = Db_Booking::getBookings("cart_id = ".$cartId);
                    $time = date('H:i:s d-m-Y',$booking[0]['time_c']);
                    //var_dump(WEB_DOMAIN, WEB_ROOT);die;
                    $display->add('webDomain',WEB_ROOT);
                    $display->add('cartContact',$cart_contact);
                    $display->add('cart',$cart);
                    $display->add('time',$time);
                    $display->add('booking',$booking);
                    $subject = 'Đơn hàng thành công trên '.WEB_DOMAIN.'!(#'.$cartId.')';
                    $messenger = $display->output('send_mail_order', true, 'SendMail');
                    if(TEST_SEND_EMAIL == 1){
                        if(in_array($cart_contact['email'],CGlobal::$email_dev) !== false){
                            if(System::sendECEmail($cart_contact['email'],$subject,$messenger)){
                                // update send mail status
                                DB::update_id('cart', array("send_mail" => 1), $cartId, __FILE__ . ' line ' . __LINE__);
                                $url =WEB_ROOT;
                            }
                        }
                    }else{
                        if(System::sendECEmail($cart_contact['email'],$subject,$messenger)){
                            // update send mail status
                            DB::update_id('cart', array("send_mail" => 1), $cartId, __FILE__ . ' line ' . __LINE__);
                        }else{
                            //var_dump($messenger);
                            DB::update_id('cart', array("send_mail" => -1), $cartId, __FILE__ . ' line ' . __LINE__);
                        }
                    }

                }
            }
        }
    }
}
?>